/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
// 															  
//             Copyright(c) 2024 XLX
//	              All rights reserved.	
// XLX:   Kenglee						
// Time: 2024-8-21        			 
// File name:		xlx_esp32xx_queue.c	               				
// Software version: 	1.0							
// Function:  	队列
 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

#include <string.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "xlx_queue.h"
#include "xlx_platform.h"

static const char* TAG = "Que";

static char tutuqueue_create(TutuQueueHandle *handle,int size){
    QueueHandle_t q = xQueueCreate(size, sizeof(TutuQueueMsg*));
    
    if(q){
        *handle = q;
        return 1;
    }
    TUTU_LOGI(TAG, "%s() line:%d create queue failt!\n",__FUNCTION__,__LINE__);
    return 0;
}

static char tutuqueue_send(TutuQueueHandle handle,TutuQueueMsg*msg){
    QueueHandle_t q = handle;

    TUTU_LOGI(TAG, "Q_send@%p,id=%d,len=%d", handle,msg->msg_id,msg->data_len);
    if (q){   
        TutuQueueMsg *m = NULL;//
        m = (TutuQueueMsg *)TUTUAlloc(sizeof(TutuQueueMsg));
        if(m){
            m->msg_id = msg->msg_id;
            m->data_len = msg->data_len;
            m->data = msg->data;
            BaseType_t code = xQueueSend((QueueHandle_t)q, (const void *)&m, 0); // 看其他参考，这个地方是0
            if (pdTRUE == code){
                return 1;
            }            
            TUTUFree(m);
        } else {
            TUTU_LOGI(TAG, "Queue malloc is failed!");
        }
        
    }
    return 0;
}

/*
* timeout： 单位是秒
*/
static char tutuqueue_recv(TutuQueueHandle handle,TutuQueueMsg *recvMsg, float timeout){
    TutuQueueMsg *r = NULL;
    if (handle && (xQueueReceive((QueueHandle_t)handle, (void *)&r, (TickType_t)((timeout*1000) / portTICK_PERIOD_MS)) == pdTRUE)) {
        memcpy(recvMsg,r,sizeof(TutuQueueMsg));
        TUTUFree(r);
        return 1;
    }

    return 0;
}

static void tutuqueue_del(TutuQueueHandle handle){
    if(handle){
        vQueueDelete((QueueHandle_t)handle);
    }
}

static int tutuqueue_count(TutuQueueHandle handle) {
    return uxQueueMessagesWaiting ((QueueHandle_t)handle);
}

//初始化
void TutuQueue_Init(TutuQueue *myself){
    TUTU_LOGI(TAG, "%s(%d)", __FUNCTION__, __LINE__); 
    myself->icreate = tutuqueue_create;
    myself->idel = tutuqueue_del;
    myself->irecv = tutuqueue_recv;
    myself->isend = tutuqueue_send;
    myself->iCount = tutuqueue_count;

    TUTU_LOGI(TAG, "sys_init: %s(%d)", __FUNCTION__, __LINE__);    
}